package com.jintoufs.web.action.banner;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jhj.common.util.JhjResponseUtil;
import com.jintoufs.dao.QueryFilters;
import com.jintoufs.domain.banner.Banner;
import com.jintoufs.domain.user.User;
import com.jintoufs.logAnnotation.SystemControllerLog;
import com.jintoufs.service.banner.BannerService;
import com.jintoufs.util.valid.ValidUtil;
import com.jintoufs.web.action.shiro.bind.annotation.CurrentUser;
import com.jintoufs.web.action.support.JqgridPage;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jintoufs.util.ResponseUtil.writeInfo;

/**
 * banner管理
 * Created by xufei on 2017/12/21.
 */
@Controller
@Scope("prototype")
@RequestMapping("/banner")
public class BannerAction {
    @Resource
    private BannerService bannerService;

    /**
     * Banner信息查询
     * @return
     * @throws IOException
     */
    @RequestMapping("/list")
    public String list() throws IOException {
        return "banner/list";
    }

    @RequestMapping("/query")
    @ResponseBody
    public JqgridPage query(int page, int rows, String sidx, String sord, String filters) {
        PageHelper.startPage(page, rows);
        QueryFilters filters_ = null;
        if (ValidUtil.isEmpty(filters)) {
            filters_ = new QueryFilters();
        } else {
            filters_ = JSON.parseObject(filters, QueryFilters.class);
        }
        if (ValidUtil.isEmpty(sidx)){
            sidx="sort";
        }
        filters_.setSidx(sidx);
        filters_.setSord(sord);
        List<Map<String,Object>> list = bannerService.getByFilter(filters_);
        // 用PageInfo对结果进行包装
        PageInfo pageInfo = new PageInfo(list);
        return new JqgridPage(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(),
                pageInfo.getList());
    }

    /**
     * input.do?id= 进入banner编辑与新增页面 <br>*
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "input", method = RequestMethod.GET)
    public String input(Integer id, Model model) {
        Map map = new HashMap();
        // 是否为编辑保存
        Boolean isEdit = false;

        if (id != null) {
            // 修改
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("id", id);
            List<Map<String,Object>> list = bannerService.queryByParams(params);
            if (list != null && list.size() > 0) {
                map = list.get(0);
            }
            isEdit = true;
        } else {
            // 新增
        }

        model.addAttribute("isEdit", isEdit);
        model.addAttribute("entity", map);
        return "banner/input";
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    @SystemControllerLog(description = "新增banner")
    public void save(Banner banner, HttpServletResponse response, @CurrentUser User user) throws ParseException {
        String error = null;
        if(banner.getCreateUserId() == null && "".equals(banner.getCreateUserId())){
            error = "输入创建用户id不能为空！";
        }
        if(banner.getDirectUrl() == null && "".equals(banner.getDirectUrl())){
            error = "指向路径不能为空！";
        }
        if(banner.getImageUrl() == null && "".equals(banner.getImageUrl())){
            error = "图片路径不能为空！";
        }
        if(banner.getTitle() == null && "".equals(banner.getTitle())){
            error = "标题不能为空！";
        }


        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time=format.format(new Date());
        banner.setCreateTime(format.parse(time));
        banner.setCreateUserId(user.getId().toString());
        Map<String, Object> result = bannerService.save(banner);
        JhjResponseUtil.responseJson(response, JSON.toJSONString(result));
    }




    @RequestMapping("delete")
    @SystemControllerLog(description = "删除banner")
    public void delete(HttpServletResponse response, String[] id) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            for (String _id : id) {
                bannerService.delete(Integer.valueOf(_id));
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof DataIntegrityViolationException) {
                ajaxMsg.setCode("500");
                ajaxMsg.setMessage("banner还在使用中，删除失败！");
            }
        }
        writeInfo(response, JSON.toJSONString(ajaxMsg));
    }

    /**
     * 获取详细信息
     */
    @RequestMapping("/getDetail")
    @SystemControllerLog(description = "查看banner详细信息")
    public String getDetail(Integer id, Model model) {
        Map<String,Object> result = new HashMap<>();
        if (id != null && id != 0) {
            result = bannerService.getById(id);
        }
        model.addAttribute("entity", result);
        model.addAttribute("isEdit", "view");
        model.addAttribute("title", "banner详细信息");
        return "banner/detail";
    }

    @RequestMapping("display")
    @ResponseBody
    public AjaxMsg display(Integer id){
        AjaxMsg ajaxMsg = new AjaxMsg();
        if (id!=null){
            Banner banner = bannerService.selectById(id);
            if (banner != null){
                banner.setDisplay(!banner.getDisplay());
                bannerService.save(banner);
            }else {
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setMessage("服务器异常，请稍后重试。");
            }
        }else {
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("服务器异常，请稍后重试。");
        }
        return ajaxMsg;
    }
    @RequestMapping("/red/{id}")
    public String redImg(@PathVariable Integer id, Model model, HttpServletRequest request){
        try {
            Banner banner = bannerService.selectById(id);
            model.addAttribute("url",banner.getImageUrl());
            return "/images/display";
        }catch (Exception e){
            e.printStackTrace();
            return request.getHeader("Referer");
        }
    }
}
